const { Menu, dialog } = require("electron");
const got = require("got");
const imageType = require("image-type");
const randomstring = require("randomstring");
const path = require("path");
const fs = require("fs");

const saveas = (srcURL) => {
    if (srcURL) {
        const contextMenu = Menu.buildFromTemplate([
            {
                label: "图片另存为",
                click: () => {
                    got.get(srcURL).then(async response => {
                        const chunk = Buffer.from(response.rawBody);
                        const ImageType = imageType(chunk);
                        const { filePath, canceled } = await dialog.showSaveDialog({
                            title: "图片另存为",
                            defaultPath: path.resolve(__dirname, "../public/uploads/" + randomstring.generate(8) + "." + ImageType.ext)
                        });
                        if (!canceled) {
                            console.log(filePath)
                            fs.writeFileSync(filePath, chunk);
                        }
                    }).catch(e => { })
                },
                accelerator: "CommandOrControl + s"
            }
        ]);
        contextMenu.popup();
    }
};
module.exports = saveas;